<?php
namespace App\Libs\Goods;
use \Phalcon\DI;
use \App\Libs\Cache\Redis;
use \App\Libs\DB\PailePdo;
/**
 * 生成orderSn
 */
class OrderSn extends \App\Libs\Base\AccessObject
{

    public static function getOrderSn( $type = 11 ){

        // if (empty($orderSnNum)) {
        //     $orderSnNum = self::setOrderSn() + 1;
        // }
        
        $orderSnNum = self::setOrderSn() + 1;

        $orderSn = str_pad ( $orderSnNum ,  5 , 0 ,  STR_PAD_LEFT );

        $orderSn = $type.date('YmdHis').$orderSn;

        // //查看数据库是否存在此订单
        $sql = "SELECT id FROM t_paile_order WHERE order_sn = ?";
        $res = PailePdo::find($sql , [$orderSn]);

        if (!empty($res)) {
            //查询分类最大订单号
            $sql = "SELECT max(order_sn) as order_sn FROM t_anxin_order";
            $res = PailePdo::find($sql)['order_sn'];

            //获取自增5位数
            $orderSnNum = (int)substr($res, -5) + 1;

            //生成新的订单号
            $orderSn = $type.date('YmdHis').$orderSn;
            //存入redis
            \App\Libs\Cache\Redis::set('orderSn', $orderSnNum );
        }else{
            \App\Libs\Cache\Redis::set('orderSn', $orderSnNum );
        }

        return $orderSn;
    }

    public static function setOrderSn(){
        $res = \App\Libs\Cache\Redis::get('orderSn')?\App\Libs\Cache\Redis::get('orderSn'):0;
        //
        if ($res >= 99999) {
            $res = 0;
        }

        return $res;
    }
}


